package com.example.clear;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageDataObserver;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.RemoteException;
import android.util.Log;
import android.widget.TextView;

import java.io.File;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class AsyncTaskScan extends AsyncTask<Void, Void, Long> {
    private Method mGetPackageSizeInfoMethod, mFreeStorageAndNotifyMethod;
    PackageManager packageManager;
    ActivityManager activityManager;
    Activity context;
    TextView textTotal;
    TextView textLog;
    StringBuilder sb;

    public AsyncTaskScan(Activity context, TextView textTotal, TextView textLog) {
        this.context = context;
        this.textTotal = textTotal;
        this.textLog = textLog;
        try {
            packageManager = context.getPackageManager();
            activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

            mGetPackageSizeInfoMethod = context.getPackageManager().getClass().getMethod(
                    "getPackageSizeInfo", String.class, IPackageStatsObserver.class);

            mFreeStorageAndNotifyMethod = context.getPackageManager().getClass().getMethod(
                    "freeStorageAndNotify", long.class, IPackageDataObserver.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        sb = new StringBuilder();
    }

    @Override
    protected Long doInBackground(Void... voids) {
        long toatal = 0L;
        final List<ApplicationInfo> packages = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
        List<AppProcessInfo> list = new ArrayList<>();
        for (ApplicationInfo appInfo : packages) {
            AppProcessInfo processInfo = new AppProcessInfo(appInfo.processName, appInfo.uid, appInfo.uid);
            processInfo.isSystem = (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
            Drawable icon = appInfo.loadIcon(packageManager);
            String appName = appInfo.loadLabel(packageManager).toString();
            processInfo.icon = icon;
            processInfo.appName = appName;
            processInfo.packName = appInfo.packageName;
            Context mContext = null;
            try {
                mContext = context.createPackageContext(appInfo.packageName, Context.CONTEXT_IGNORE_SECURITY);
                // Context.getExternalFilesDir() --> SDCard/Android/data/你的应用的包名/files/
                // 目录，一般放一些长时间保存的数据
                // Context.getExternalCacheDir() --> SDCard/Android/data/你的应用包名/cache/
                // 目录，一般存放临时缓存数据
                processInfo.memory = ExternalUtil.getTotalCacheSize(Objects.requireNonNull(mContext));
                list.add(processInfo);

                if(processInfo.memory > 0){
                    String typeName = processInfo.isSystem ? "系统应用" : "本地应用";
                    final String content = typeName + processInfo.appName + "-Cache:" + ExternalUtil.size(processInfo.memory);
                    Log.d("ddd", content);
                    toatal += processInfo.memory;

                    final long finalToatal = toatal;
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textTotal.setText(String.format("缓存总大小为 ： %s", ExternalUtil.size(finalToatal)));
                            sb.append(content).append("\r\n");
                            textLog.setText(sb.toString());
                        }
                    });
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        ExternalUtil.getProcessInfo(context);
        return null;
    }

    private void scanCache() {
        List<PackageInfo> installedPackages = packageManager.getInstalledPackages(0);
        for (PackageInfo info : installedPackages) {
            try {
                Method getPackageSizeInfo = packageManager.getClass().getDeclaredMethod("getPackageSizeInfo", String.class, IPackageStatsObserver.class);
                getPackageSizeInfo.invoke(packageManager, info.packageName, new MyDataObserver());

//                Context mContext = context.createPackageContext(info.packageName, Context.CONTEXT_IGNORE_SECURITY);
//                File cacheDirectory = mContext.getCacheDir();
//                if (cacheDirectory == null) {
//                    Log.d("ddd", info.packageName + "-Cache:" + 0);
//                } else {
//                    String s = String.valueOf(cacheDirectory.length() / 1024);
//                    Log.d("ddd", info.packageName + "-Cache:" + s);
//                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private class MyDataObserver extends IPackageStatsObserver.Stub {
        @Override
        public void onGetStatsCompleted(PackageStats pStats, boolean succeeded)
                throws RemoteException {
            final long cache = pStats.cacheSize; //应用缓存的大小
            long code = pStats.codeSize;
            long data = pStats.dataSize;//这里便可以拿到应用数据的大小
            String packageName = pStats.packageName;
            ApplicationInfo appinfo = null;
            try {
                appinfo = packageManager.getApplicationInfo(packageName, 0);
                Log.d("ddd", appinfo.packageName + "--Cache:" + cache + ";Code:" + code);
            } catch (PackageManager.NameNotFoundException ex) {
                ex.printStackTrace();
            }
        }
    }

}
